package com.hu.example.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hu.core.util.StringUtil;
import com.hu.example.Constants;
import com.hu.example.domain.model.User;

public class SessionFilter implements Filter {
    private String noAuthPages = "";
    protected FilterConfig filterConfig;

    @Override
    public void destroy() {
        this.noAuthPages = null;
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        String uri = request.getRequestURI();
        String requestUri = uri.substring(request.getContextPath().length() + 1);
        String queryString = request.getQueryString();
        System.out.println(requestUri);
        String[] pages = noAuthPages.split(",");
        boolean isAllow = false;
        for (String page : pages) {
            if (page.equals(requestUri)) {
                isAllow = true;
                break;
            }
        }

        if (isAllow) {
            filterChain.doFilter(request, response);
        } else {
            HttpSession session = request.getSession();
            User user = (User)session.getAttribute(Constants.USER);
            if (null == user) {
                if ("get".equals(request.getMethod().toLowerCase())) {
                    if (!StringUtil.isEmpty(queryString)) {
                        requestUri = requestUri + "#" + queryString;
                    }

                    response.sendRedirect(request.getContextPath() + "/login.action?" + Constants.LAST_VIEW_PAGE + "=" + requestUri);
                } else {
                    response.sendRedirect(request.getContextPath() + "/login.action");
                }

            } else {
                filterChain.doFilter(request, response);
            }
        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        noAuthPages = null == filterConfig.getInitParameter(Constants.NO_AUTH_PAGES) ? "" : filterConfig.getInitParameter(Constants.NO_AUTH_PAGES);
    }
}
